package com.tbit.uqbike.client.util.http;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tbit.uqbike.client.pojo.AccountPhoneLogin;
import com.tbit.uqbike.client.util.HttpClientUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import java.io.UnsupportedEncodingException;
import java.util.*;

/**
 * @Author: chen
 * @Description: 网易易盾一键登录
 * @Date: 创建于 11:07 2020/11/11
 */
@Slf4j
public class WyydLoginUtil {

    /**
     * 产品密钥ID，产品标识
     */
    private final static String SECRETID = "bf04a7e1d10877caa5dd235ff9bb6fe3";

    /**
     * 产品私有密钥，服务端生成签名信息使用，请严格保管，避免泄露
     */
    private final static String SECRETKEY = "69349441c3e1d0caafc0fa8461695a08";

    /**
     * 业务ID，易盾根据产品业务特点分配
     */
    private final static String BUSINESSID = "b5715c7481de4ff2a2da8eb073d0dc0c";

    /**
     * 本机认证服务身份证实人认证在线检测接口地址
     */
    private final static String API_URL = "https://ye.dun.163yun.com/v1/oneclick/check";


    /**
     * 获取手机号码
     *
     * @return
     */
    public static String onLineCheck(String token, String accessToken) {
        Map<String, String> params = new HashMap<String, String>();
        // 1.设置公共参数
        params.put("secretId", SECRETID);
        params.put("businessId", BUSINESSID);
        params.put("version", "v1");
        params.put("timestamp", String.valueOf(System.currentTimeMillis())); // 格式为时间戳格式, 与当前时间差值不能超过6s
        params.put("nonce", UUID.randomUUID().toString().replace("-", "")); // 32随机字符串
        // 2.设置私有属性
        params.put("accessToken", accessToken); // 运营商预取号获取到的token
        params.put("token", token); // 易盾返回的token
        // accessToken, token都是一次性有效, 且2分钟后自动过期
        // 3.生成签名信息
        String signature = null;
        try {
            signature = genSignature(SECRETKEY, params);
        } catch (UnsupportedEncodingException e) {
            log.error(e.getMessage(), e);
        }
        params.put("signature", signature);
        // 4.发送HTTP请求，这里使用的是HttpClient工具包
        List<NameValuePair> list = new ArrayList<>();
        Iterator<Map.Entry<String, String>> itr = params.entrySet().iterator();
        while (itr.hasNext()) {
            Map.Entry<String, String> entry = itr.next();
            list.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }
        String response = HttpClientUtils.httpPost(API_URL, null, list);

        JSONObject resultJson = JSON.parseObject(response);
        if (resultJson.getInteger("code").equals(200)) {
            JSONObject data = resultJson.getJSONObject("data");
            String phone = data.getString("phone");
            if (StringUtils.isNotEmpty(phone)) {
                return phone;
            } else {
                String resultCode = data.getString("resultCode");
                System.out.println("运营商返回码:" + resultCode);
                return null;
            }
        } else {
            return null;
        }
    }

    /**
     * 获取手机号码
     *
     * @param token
     * @param accessToken
     * @param login       配置信息
     * @return.l
     */
    public static String getPhone(String token, String accessToken, AccountPhoneLogin login) {
        Map<String, String> params = new HashMap<String, String>();
        // 1.设置公共参数
        params.put("secretId", login.getSecretId());
        params.put("businessId", login.getBusinessId());
        params.put("version", "v1");
        params.put("timestamp", String.valueOf(System.currentTimeMillis())); // 格式为时间戳格式, 与当前时间差值不能超过6s
        params.put("nonce", UUID.randomUUID().toString().replace("-", "")); // 32随机字符串
        // 2.设置私有属性
        params.put("accessToken", accessToken); // 运营商预取号获取到的token
        params.put("token", token); // 易盾返回的token
        // accessToken, token都是一次性有效, 且2分钟后自动过期
        // 3.生成签名信息
        String signature = null;
        try {
            signature = genSignature(login.getSecretKey(), params);
        } catch (UnsupportedEncodingException e) {
            log.error(e.getMessage(), e);
        }
        params.put("signature", signature);
        // 4.发送HTTP请求，这里使用的是HttpClient工具包
        List<NameValuePair> list = new ArrayList<>();
        Iterator<Map.Entry<String, String>> itr = params.entrySet().iterator();
        while (itr.hasNext()) {
            Map.Entry<String, String> entry = itr.next();
            list.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }
        String response = HttpClientUtils.httpPost(API_URL, null, list);

        JSONObject resultJson = JSON.parseObject(response);
        if (resultJson.getInteger("code").equals(200)) {
            JSONObject data = resultJson.getJSONObject("data");
            String phone = data.getString("phone");
            if (StringUtils.isNotEmpty(phone)) {
                return phone;
            } else {
                String resultCode = data.getString("resultCode");
                System.out.println("运营商返回码:" + resultCode);
                return null;
            }
        } else {
            return null;
        }
    }

    /**
     * 签名
     *
     * @param secretKey 鉴权秘钥
     * @param params    签名参数
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String genSignature(String secretKey, Map<String, String> params) throws UnsupportedEncodingException {
        // 1. 参数名按照ASCII码表升序排序
        String[] keys = params.keySet().toArray(new String[0]);
        Arrays.sort(keys);

        // 2. 按照排序拼接参数名与参数值
        StringBuffer paramBuffer = new StringBuffer();
        for (String key : keys) {
            paramBuffer.append(key).append(params.get(key) == null ? "" : params.get(key));
        }
        // 3. 将secretKey拼接到最后
        paramBuffer.append(secretKey);

        // 4. MD5是128位长度的摘要算法，用16进制表示，一个十六进制的字符能表示4个位，所以签名后的字符串长度固定为32个十六进制字符。
        return DigestUtils.md5Hex(paramBuffer.toString().getBytes("UTF-8"));
    }

    public static void main(String[] args) {
        System.out.println(onLineCheck("961373d92ebb414080275252d5f23da0", "STsid0000001605248251111bwOvAvYkzM0YqqwwmX2UgwcIfMW1z1ou"));
    }
}
